<?php

namespace App\Http\Middleware;

use App\Models\Rbac\User;
use App\Rep\EmployeeRep;
use App\Rep\NumberExtractorRep;
use App\Rep\Rbac\UserRep;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;


class ConnectDB
{
    /**
     * 连接数据库
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse)  $next
     * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
     */
    public function handle(Request $request, Closure $next)
    {
        try {

            $token = $request->header("token")??$request->get('token');
            if(empty($token)){
                $parent_username = $request->get('parent_username');
            }else{
                $user_info = UserRep::getUserInfoForToken($token);
                if(empty($user_info)){
                    return re(5001,'','登录过期');
                }else{
                    $parent_username = $user_info['parent_username'];
                }
            }

            if(empty($parent_username)){
                return re(1009,'','1009账户不可用,请联系管理员');
            }

            $dbName = 'db_'.$parent_username;
            $request->offsetSet("dbName",$dbName);
            $request->offsetSet("parent_username",$parent_username);

            //DB::purge('mysql');
            Config::set('database.connections.mysql.database', $dbName);
            DB::connection()->getPdo();
            if(DB::connection()->getDatabaseName()){
                //Log::channel('dblog')->info("数据库连接成功 DB: " . DB::connection()->getDatabaseName());

                $info = User::where('username',$parent_username)->first();
                //p($info);
                if(!$info){
                    return re(1000,$parent_username);
                }

                return $next($request);
            }else{
                //Log::channel('dblog')->info("无法找到数据库。请检查您的配置。");
                return re(4006);
            }
        } catch (\Exception $e) {
            //Log::channel('dblog')->info("无法打开到数据库服务器的连接。请检查您的配置。".$e->getMessage());
            return re(1003,'',$e->getMessage());
        }

    }
}
